package com.yaowk.authc.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.log.Log;
import com.yaowk.authc.model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

/**
 * @authc yaowk
 * 2017/6/23
 */
public class GuestInterceptor implements Interceptor {
    @Override
    public void intercept(Invocation inv) {
        if (!("login".equals(inv.getMethodName()))) {
            Subject subject = SecurityUtils.getSubject();
            try {
                if (!subject.isAuthenticated()) {
                    AuthenticationToken token = new UsernamePasswordToken("guest", "123456");
                    subject.login(token);
                    subject.getSession().setTimeout(-1000L);
                    User user = (User) subject.getPrincipal();
                    int platformId = Integer.valueOf(inv.getController().getHeader("platform_id"));
                    user.setPlatformId(platformId);
                }
            }
            catch (Exception e) {
                Log.getLog("").error("guest error", e.getCause());
            }
        }
        inv.invoke();
    }
}
